package com.css.zfzx.sjcj.modules.qhdrillhistogram.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.components.attach.repository.entity.SysAttachmentEntity;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.modules.qhdrillhistogram.repository.QhDrillHistogramNativeRepository;
import com.css.zfzx.sjcj.modules.qhdrillhistogram.repository.QhDrillHistogramRepository;
import com.css.zfzx.sjcj.modules.qhdrillhistogram.repository.entity.QhDrillHistogramEntity;
import com.css.zfzx.sjcj.modules.qhdrillhistogram.service.QhDrillHistogramService;
import com.css.zfzx.sjcj.modules.qhdrillhistogram.viewobjects.QhDrillHistogramQueryParams;
import com.css.zfzx.sjcj.modules.qhdrillhistogram.viewobjects.QhDrillHistogramVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.modules.qhdrilloverview.repository.QhDrillOverviewRepository;
import com.css.zfzx.sjcj.modules.qhdrilloverview.repository.entity.QhDrillOverviewEntity;
import com.css.zfzx.sjcj.modules.qhdrilloverview.viewobjects.QhDrillOverviewVO;
import com.css.zfzx.sjcj.modules.sysattachmentinfo.repository.SysAttachmentinfoRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author aa
 * @date 2020-11-11
 */
@Slf4j
@Service
public class QhDrillHistogramServiceImpl implements QhDrillHistogramService {

	@Autowired
    private QhDrillHistogramRepository qhDrillHistogramRepository;
    @Autowired
    private QhDrillHistogramNativeRepository qhDrillHistogramNativeRepository;
    @Autowired
    private QhDrillOverviewRepository qhDrillOverviewRepository;
    @Autowired
    private SysAttachmentinfoRepository sysAttachmentinfoRepository;

    @Override
    public JSONObject queryQhDrillHistograms(QhDrillHistogramQueryParams queryParams, int curPage, int pageSize) {
        Page<QhDrillHistogramEntity> qhDrillHistogramPage = this.qhDrillHistogramNativeRepository.queryQhDrillHistograms(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(qhDrillHistogramPage);
        return jsonObject;
    }


    @Override
    public QhDrillHistogramEntity getQhDrillHistogram(String id) {
        QhDrillHistogramEntity qhDrillHistogram = this.qhDrillHistogramRepository.findById(id).orElse(null);
         return qhDrillHistogram;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhDrillHistogramEntity saveQhDrillHistogram(QhDrillHistogramEntity qhDrillHistogram) {
        String uuid = UUIDGenerator.getUUID();
        qhDrillHistogram.setId(uuid);
        qhDrillHistogram.setCreateUser(PlatformSessionUtils.getUserId());
        qhDrillHistogram.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        qhDrillHistogram.setIsValid("1");
        qhDrillHistogram.setReviewStatus("0");
        qhDrillHistogram.setQualityinspectionStatus("0");
        this.qhDrillHistogramRepository.save(qhDrillHistogram);
        return qhDrillHistogram;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhDrillHistogramEntity updateQhDrillHistogram(QhDrillHistogramEntity qhDrillHistogram) {
        qhDrillHistogram.setUpdateUser(PlatformSessionUtils.getUserId());
        qhDrillHistogram.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.qhDrillHistogramRepository.save(qhDrillHistogram);
        return qhDrillHistogram;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQhDrillHistograms(List<String> ids) {
        List<QhDrillHistogramEntity> qhDrillHistogramList = this.qhDrillHistogramRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(qhDrillHistogramList) && qhDrillHistogramList.size() > 0) {
            for(QhDrillHistogramEntity qhDrillHistogram : qhDrillHistogramList) {
//                this.qhDrillHistogramRepository.delete(qhDrillHistogram);
                qhDrillHistogram.setUpdateUser(PlatformSessionUtils.getUserId());
                qhDrillHistogram.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                qhDrillHistogram.setIsValid("0");
                this.qhDrillHistogramRepository.save(qhDrillHistogram);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitQhDrillHistograms(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhDrillHistogramEntity> qhDrillHistogramList = this.qhDrillHistogramRepository.findAllById(idList);
        if(!PlatformObjectUtils.isEmpty(qhDrillHistogramList) && qhDrillHistogramList.size() > 0) {
            for(QhDrillHistogramEntity qhDrillHistogram : qhDrillHistogramList) {
                qhDrillHistogram.setUpdateUser(PlatformSessionUtils.getUserId());
                qhDrillHistogram.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                qhDrillHistogram.setReviewStatus("1");
                this.qhDrillHistogramRepository.save(qhDrillHistogram);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String importExcel(MultipartFile file) {
        return this.importExcel(file,new HashMap<>());
    }

    @Override
    public String importExcel(MultipartFile file, Map<String,String> attachmentMap) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            params.setTitleRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<QhDrillHistogramVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), QhDrillHistogramVO.class, params);
            List<QhDrillHistogramVO> list = result.getList();
            //处理附件信息
            for(QhDrillHistogramVO dhVo : list) {
                String attachment = dhVo.getAttachment();
                dhVo.setAttachment(attachmentMap.containsKey(attachment) ? attachmentMap.get(attachment) : attachment);
            }
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<QhDrillHistogramVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    QhDrillHistogramVO areaVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + areaVO.getRowNum() + "行" + areaVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public String exportExcel(String ids, HttpServletResponse response) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhDrillHistogramEntity> areaEntities = this.qhDrillHistogramRepository.findAllById(idList);

        return exportExcel(areaEntities,response);
    }

    @Override
    public String exportExcel(List<QhDrillHistogramEntity> entities, HttpServletResponse response)
    {
        try {
            // 深拷贝
            ArrayList<QhDrillHistogramVO> vos = new ArrayList<>();
            for (QhDrillHistogramEntity areaEntity : entities) {
                QhDrillHistogramVO vo = new QhDrillHistogramVO();
                BeanUtils.copyProperties(areaEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "钻孔综合柱状图采集", "钻孔综合柱状图", QhDrillHistogramVO.class, "钻孔综合柱状图.xls", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private void saveExcel(List<QhDrillHistogramVO> list) {
        for (int i = 0; i < list.size(); i++) {
            QhDrillHistogramEntity areaEntity = new QhDrillHistogramEntity();
            QhDrillHistogramVO areaVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(areaVO, areaEntity);
            String attchName = areaVO.getAttachment();
            if (StringUtils.isNotBlank(attchName)) {
                // 根据文件名称获取附件表信息
                List<SysAttachmentEntity> attachmentEntities = sysAttachmentinfoRepository.findByAttachNameAndIsValid(attchName, "1");
                if (attachmentEntities.size() > 0) {
                    String attachId = attachmentEntities.get(0).getAttachId();
                    areaEntity.setAttachment(attachId);
                }
            }
            saveQhDrillHistogram(areaEntity);
        }
    }

    @Override
    public JSONObject checkCoordinate(String ids) {
        List<String> codeList = new ArrayList<>();
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhDrillHistogramEntity> qhDrillHistogramList = this.qhDrillHistogramRepository.findAllById(idList);
        boolean hadData = !PlatformObjectUtils.isEmpty(qhDrillHistogramList) && qhDrillHistogramList.size() > 0;
        if(hadData) {
            for(QhDrillHistogramEntity qhDrillHistogram : qhDrillHistogramList) {
                String drillCode = qhDrillHistogram.getDrillCode();
                codeList.add(drillCode);
            }
        }

        List<String> drillHistogramCodes = new ArrayList<>();
        if(hadData && codeList.size() > 1) {
             List<QhDrillOverviewEntity> qhDrillOverviewsList = qhDrillOverviewRepository.findByIsValidAndDrillCodeIn("1",codeList);
            if(!PlatformObjectUtils.isEmpty(qhDrillOverviewsList) && qhDrillOverviewsList.size() > 0) {
                for(QhDrillOverviewEntity qhDrillOverview : qhDrillOverviewsList) {
                    String drillCodeOE = qhDrillOverview.getDrillCode();
                    String drillXOE = qhDrillOverview.getDrillX();
                    String drillYOE = qhDrillOverview.getDrillY();

                    for(QhDrillHistogramEntity qhDrillHistogram : qhDrillHistogramList) {
                        String drillCodeHE = qhDrillHistogram.getDrillCode();
                        String drillXHE = qhDrillHistogram.getDrillX();
                        String drillYHE = qhDrillHistogram.getDrillY();
                        if(drillCodeHE.equals(drillCodeOE) && (!drillXHE.equals(drillXOE) || !drillYHE.equals(drillYOE))) {
                            String id = qhDrillHistogram.getId();
                            drillHistogramCodes.add(id);
                        }
                    }
                }
            }
        }

        JSONObject json = new JSONObject();
        json.put("data",drillHistogramCodes);
        if(drillHistogramCodes.size() > 0) {
            json.put("message", "共" + drillHistogramCodes.size() + "条数据校验未通过");
        } else {
            json.put("message", "数据校验通过");
        }

        return json;
    }
}
